package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItem.setCreateTime(new Date());
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
//        修改逻辑:
//        1.如果是上架状态，不允许修改的,抛出异常
//        2.如果是下架状态
//        非套餐(不需要处理)
//        套餐，如果是审核中,不能进行编辑，抛出异常
//        如果是下架状态，套餐，处于审核通过,如果此时修改，应该把状态修改成初始化
//        其他情况，原来是什么状态，应该设置什么状态.
//                非套餐--->无需审核
//        套餐   ---->初始化，重新发起
//        防止前台恶意对销售状态进行设置，代码中主动设置销售状态为下架状态
        ServiceItem oldServiceItem = this.get(serviceItem.getId());
        if (ServiceItem.SALESTATUS_ON.equals(oldServiceItem.getSaleStatus())) {
            throw new BusinessException("服务已经上架，无法修改");
        }

        if (!ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())) { // 判读是否是套餐
            if (ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())) { // 判读是否正在审核
                throw new BusinessException("该服务正在审核，无法修改");
            }
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            // 能过来的都是非套餐的
            serviceItem.setAuditStatus(oldServiceItem.getAuditStatus());
        }

        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);

        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOff(Long id) {
        serviceItemMapper.saleOff(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem oldServiceItem = serviceItemMapper.selectByPrimaryKey(id);
        if (ServiceItem.CARPACKAGE_YES.equals(oldServiceItem.getCarPackage()) && ServiceItem.AUDITSTATUS_APPROVED.equals(oldServiceItem.getAuditStatus())) {
            throw new BusinessException("正在审核无法上架");
        }
        serviceItemMapper.saleOn(id,ServiceItem.SALESTATUS_ON);


    }

    @Override
    public void startAudit(Long id, Long bpmnInfoId, Long director, Long finance, String info) {
        // 判断是否处于初始化或者重新调整
        ServiceItem oldServiceItem = this.get(id);
        if (!(ServiceItem.AUDITSTATUS_INIT.equals(oldServiceItem.getSaleStatus())||
                ServiceItem.AUDITSTATUS_REPLY.equals(oldServiceItem.getSaleStatus())) ) {
            throw new BusinessException("非法操作!");
        }
        // 修改状态
        serviceItemMapper.changeAuditStatus(id, ServiceItem.AUDITSTATUS_AUDITING);
        System.out.println(oldServiceItem.getSaleStatus());
        // 创建对象
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(id);
        audit.setServiceItemInfo(oldServiceItem.getInfo());
        audit.setServiceItemPrice(oldServiceItem.getDiscountPrice());
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(director);
        carPackageAuditMapper.insert(audit);
        // 启动流程
        Map<String,Object> map = new HashMap<>();
        if (director != null) {
            map.put("director",director.toString());
        }

        if (finance != null) {
            map.put("finance",finance.toString());
        }

        map.put("discountPrice",oldServiceItem.getDiscountPrice().longValue());
        // 然后把流程实例对象存到对象当中
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(bpmnInfoId);
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey(bpmnInfo.getActProcessKey(), audit.getId().toString(), map);
        // 再次更新
        audit.setInstanceId(processInstance.getId());
        carPackageAuditMapper.updateByPrimaryKey(audit);

    }
}
